﻿using System;
using System.Data;
using System.Text;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Web.Script.Services;
using System.Web.Services;

using HsTec.Mobile.Green.BLL;
using HsTec.Mobile.Green.Model;
using HsTec.Mobile.Green.Util;

public partial class OnlineReport_OnlineReport : System.Web.UI.Page
{
    private ReportAnalysisBLL rab = new ReportAnalysisBLL();
    private ReportAnalysisOnlineBLL bll = new ReportAnalysisOnlineBLL();
    private string sEditStatus = String.Empty;
    private string sID = String.Empty;
    private string sAreaId = String.Empty;
    protected string fieldName = String.Empty;
    protected Dictionary<string, List<string>> dicTable = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if ((string)Session["Baimasoft_Pers_ID"] == null)
        {
            Response.Redirect("../Logon.aspx");
        }
        sAreaId = (string)Session["Baimasoft_Report"];
        //TODO:修改
        dicTable = getTableInfo();

        if (!String.IsNullOrEmpty(sAreaId) || sAreaId == "0")
        {
            hidAreaid.Value = "1";
        }
        try
        {
            sEditStatus = this.Request.QueryString["EditStatus"].ToString().Trim();
            hidID.Value = sEditStatus;
            sID = this.Request.QueryString["ID"].ToString().Trim();
        }
        catch
        { }
        if (!IsPostBack)
        {
            if (sEditStatus == "4" || sEditStatus == "2")
            {
                btnAduit.Visible = true;
                btnUnAduit.Visible = true;
                txtRemark.Visible = true;
            }
            else
            {
                btnAduit.Visible = false;
                btnUnAduit.Visible = false;
                txtRemark.Visible = false;
            }
            if (sEditStatus == "2")
            {
                txtRemark.Disabled = true;
            }
            this.BindsltArea();
            if (sEditStatus == "2" || sEditStatus == "4")
            {
                //获取所有的字段值
                editinfo.Value = getEditInfo(sID);
            }
            if (sEditStatus == "4")
            {
                an.Visible = false;
                btnAduit.Visible = true;
            }
        }
    }
    private void BindsltArea()
    {
        sltArea.DataTextField = "Name";
        sltArea.DataValueField = "ID";
        sltArea.DataSource = bll.GetAreaList(sAreaId);
        sltArea.DataBind();
        sltArea.Items.Insert(0, "请选择...");
        sltArea.Items[0].Value = "";
    }
    protected void SaveData_Click(object sender, EventArgs e)
    {
        if (sltArea.SelectedValue == "")
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择地区!');</script>");
            return;
        }
        if (sltMonth.Value == "")
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择年月!');</script>");
            return;
        }
        int Area_ID = int.Parse(this.sltArea.SelectedValue);
        string Years = this.sltYear.Value + sltMonth.Value;
        DateTime AddDate = DateTime.Now;
        //------------------------------------需要修改---------------------------------
        int OperatUser = 0;
        DateTime OperatDate = DateTime.Now;
        string AuditState = "0";

        int iBack = 0;
        if (sEditStatus == "1")
        {
            //新增
            //iBack = bll.Add(model);
            iBack = bll.AddModel(Area_ID, Years, AddDate, OperatUser, OperatDate, AuditState, txtRemark.Value, txtinfo.Value.Trim());
        }
        else
        {
            //model.RA_ID = int.Parse(sID);
            //iBack = bll.Update(model);
            //修改
            iBack = bll.EditModel(Area_ID, Years, AddDate, OperatUser, OperatDate, AuditState, txtRemark.Value, txtinfo.Value.Trim(), sID);
        }
        if (iBack == 1)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('保存成功!');self.location='OnlineReportManage.aspx';</script>");
            return;
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('保存失败!');</script>");
            return;
        }
    }
    protected void btnAduit_Click(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(sID))
        {
            if (rab.Exists(" Years='" + this.sltYear.Value + sltMonth.Value + "' and Area_ID='" + this.sltArea.SelectedValue + "'"))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('该月份数据已经入库！');</script>");
                return;
            }
            else
            {
                int iBack = bll.Aduit(sID);
                if (iBack == 1)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('审核通过!');self.location='OnlineReportManage.aspx';</script>");
                    return;
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('审核失败!');</script>");
                    return;
                }
            }
        }
    }
    protected void btnUnAduit_Click(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(sID))
        {
            if (txtRemark.Value == "")
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请在页面末尾输入审核意见，并将短信通知地市人员!');</script>");
                return;
            }
            int iBack = bll.UnAduit(sID, txtRemark.Value);
            if (iBack == 1)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('审核不通过!');self.location='OnlineReportManage.aspx';</script>");
                return;
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('审核失败!');</script>");
                return;
            }
        }
    }
    protected void btnInf_Click(object sender, EventArgs e)
    {
        if (sltArea.SelectedValue == "")
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择地区!');</script>");
            return;
        }
        if (sltMonth.Value == "")
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择年月!');</script>");
            return;
        }
        IndexFormulaBLL ifbll = new IndexFormulaBLL();
        if (sltArea.SelectedValue != "")
        {
            string tmp = String.Empty;
            DateTime lastMonth = DateTime.Parse(sltYear.Value + "-" + sltMonth.Value + "-01").AddMonths(-1);
            DateTime lastYears = DateTime.Parse(sltYear.Value + "-" + sltMonth.Value + "-01").AddYears(-1);
            DataView tmpDv = ifbll.GetIndicatorListNewArea(lastMonth.ToString("yyyy") + "01", lastMonth.ToString("yyyyMM"), sltArea.SelectedValue, "", "2");
            DataView mydv = SQLHelper.ExecuteDataView("select IndexName from tb_IndexFormula where YearState='1' and FormulaParent='3'");
            if (tmpDv.Count == 1 && mydv.Count > 0)
            {
                for (int i = 0; i < mydv.Count; i++)
                {
                    tmp += mydv[i]["IndexName"].ToString() + "变化率：" + tmpDv[0][mydv[i]["IndexName"].ToString()].ToString() + "<br/>";
                }
                labBHL.Text = tmp;
                //labBHL.Text = "单位业务量能耗变化率：" + tmpDv[0]["EnergyChange"].ToString() + "<br/>每载频通信基站耗电量变化率：" + tmpDv[0]["BaseChange"].ToString() + "<br/>单位电信业务总量综合能耗变化率：" + tmpDv[0]["TrafficChange"].ToString();
            }
            String sMarking = SQLHelper.ExecuteString("select MarkValue from tb_ForecastBusinessNew where Area_ID='" + sltArea.SelectedValue + "' and Years ='" + sltYear.Value + sltMonth.Value + "' ");
            if (String.IsNullOrEmpty(sMarking))
            {
                labBG.Text = "标杆值未录入！";
            }
            else
            {
                string s2gFlow = SQLHelper.ExecuteString("select sum(Value) from rt_2GFlow where Years = '" + sltYear.Value + sltMonth.Value + "' and Area_ID='" + sltArea.SelectedValue + "'");
                string s3gFlow = SQLHelper.ExecuteString("select sum(Value) from rt_3GFlow where Years = '" + sltYear.Value + sltMonth.Value + "' and Area_ID='" + sltArea.SelectedValue + "'");
                string sPhone = SQLHelper.ExecuteString("select sum(Value*5.85) from rt_Telephone where Years = '" + sltYear.Value + sltMonth.Value + "' and Area_ID='" + sltArea.SelectedValue + "'");
                string sTD = SQLHelper.ExecuteString("select sum(Value*5.49) from rt_TDTraffic where Years = '" + sltYear.Value + sltMonth.Value + "' and Area_ID='" + sltArea.SelectedValue + "'");
                double dTraffictmp = (Double.Parse(String.IsNullOrEmpty(s2gFlow) ? "0" : s2gFlow) +
                                Double.Parse(String.IsNullOrEmpty(s3gFlow) ? "0" : s3gFlow) +
                                Double.Parse(String.IsNullOrEmpty(sPhone) ? "0" : sPhone) +
                                Double.Parse(String.IsNullOrEmpty(sTD) ? "0" : sTD));
                //labBG.Text = "预测单位业务量能耗：" + sMarking + "度/万MB；预测耗电量：" + (double.Parse(sMarking) * dTraffictmp / 10000).ToString("0") + "度";
                double zhd = double.Parse(sMarking) * dTraffictmp / 10000;
                labBG.Text = "总耗电：" + zhd.ToString("0") + "度，基站耗电：" + (zhd * 0.62).ToString("0") + "度";
            }
            string sMonth = SQLHelper.ExecuteString("select Power from rt_EnergyConsumption where Area_ID='" + sltArea.SelectedValue + "'and Years ='" + lastMonth.ToString("yyyyMM") + "'");
            double dMonth = Double.Parse(sMonth);
            sMonth = dMonth.ToString("0");
            string sWhere = String.Empty;
            if (sltMonth.Value == "01")
            {
                sWhere = "Years >=cast('" + lastYears.Year + "01' as datetime) and Years <=cast('" + lastYears.Year + "12' as datetime)";
            }
            else
            {
                sWhere = "Years >=cast('" + lastMonth.Year + "01' as datetime)  and Years <=cast('" + lastMonth.ToString("yyyyMM") + "' as datetime)";
            }
            string sMonthLJ = SQLHelper.ExecuteString("select sum(Power) from rt_EnergyConsumption where Area_ID='" + sltArea.SelectedValue + "'and " + sWhere);
            double dMonthLJ = Double.Parse(sMonthLJ);
            sMonthLJ = dMonthLJ.ToString("0");
            labHD.Text = lastMonth.ToString("MM") + "月：" + sMonth + "度;(01-" + lastMonth.ToString("MM") + ")月累计：" + sMonthLJ + "度";
            //处理业务量显示
            //1.业务量
            string sMonth2G = SQLHelper.ExecuteString("select Value*5.85 from rt_Telephone where Area_ID='" + sltArea.SelectedValue + "'and Years = '" + lastMonth.ToString("yyyyMM") + "'");
            string sMonth2Gs = SQLHelper.ExecuteString("select sum(Value*5.85) from rt_Telephone where Area_ID='" + sltArea.SelectedValue + "'and " + sWhere);
            string sMonthTD = SQLHelper.ExecuteString("select Value*5.49 from rt_TDTraffic where Area_ID='" + sltArea.SelectedValue + "'and Years = '" + lastMonth.ToString("yyyyMM") + "'");
            string sMonthTDs = SQLHelper.ExecuteString("select sum(Value*5.49) from rt_TDTraffic where Area_ID='" + sltArea.SelectedValue + "'and " + sWhere);
            //2.话务量
            string sMonthW2G = SQLHelper.ExecuteString("select Value from rt_2GFlow where Area_ID='" + sltArea.SelectedValue + "'and Years = '" + lastMonth.ToString("yyyyMM") + "'");
            string sMonthW2Gs = SQLHelper.ExecuteString("select sum(Value) from rt_2GFlow where Area_ID='" + sltArea.SelectedValue + "'and " + sWhere);
            string sMonth3G = SQLHelper.ExecuteString("select Value from rt_3GFlow where Area_ID='" + sltArea.SelectedValue + "'and Years = '" + lastMonth.ToString("yyyyMM") + "'");
            string sMonth3Gs = SQLHelper.ExecuteString("select sum(Value) from rt_3GFlow where Area_ID='" + sltArea.SelectedValue + "'and " + sWhere);
            labYWL.Text = "2G:" + lastMonth.ToString("MM") + "月：" + sMonth2G + "ERL;(01-" + lastMonth.ToString("MM") + ")月累计：" + sMonth2Gs + "ERL" + "<br/>";
            labYWL.Text = labYWL.Text + "TD:" + lastMonth.ToString("MM") + "月：" + sMonthTD + "ERL;(01-" + lastMonth.ToString("MM") + ")月累计：" + sMonthTDs + "ERL" + "<br/>";
            labSJL.Text = "2G:" + lastMonth.ToString("MM") + "月：" + sMonthW2G + "MB;(01-" + lastMonth.ToString("MM") + ")月累计：" + sMonthW2Gs + "MB" + "<br/>";
            labSJL.Text = labSJL.Text + "3G:" + lastMonth.ToString("MM") + "月：" + sMonth3G + "MB;(01-" + lastMonth.ToString("MM") + ")月累计：" + sMonth3Gs + "MB" + "<br/>";
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>setInfo(" + sltMonth.Value + ");</script>");
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择地区!');</script>");
            return;
        }
    }
    [WebMethod]
    public static string GetStr(string sField, string sYear, string sMonth, string sAreaID)
    {
        string sYears = String.Empty;
        if (int.Parse(sMonth) <= 3)
            sYears = sYear + "01";
        else if (int.Parse(sMonth) <= 6)
            sYears = sYear + "03";
        else if (int.Parse(sMonth) <= 9)
            sYears = sYear + "06";
        else
            sYears = sYear + "09";
        string tmp = HsTec.Mobile.Green.Util.SQLHelper.ExecuteString("select TOP 1 [" + sField + "] from tb_ReportAnalysis where Years='" + sYears + "' and Area_ID='" + sAreaID + "'");
        return tmp;
    }
    [WebMethod]
    public static string GetMonth(string sYear, string sMonth, string sAreaID, string sFields, string sID)
    {
        string sYears = String.Empty;
        if (int.Parse(sMonth) <= 3)
            sYears = sYear + "01";
        else if (int.Parse(sMonth) <= 6)
            sYears = sYear + "03";
        else if (int.Parse(sMonth) <= 9)
            sYears = sYear + "06";
        else
            sYears = sYear + "09";
        DataView mydv = HsTec.Mobile.Green.Util.SQLHelper.ExecuteDataView("select TOP 1 " + sFields + "Area_ID from tb_ReportAnalysis where Years='" + sYears + "' and Area_ID='" + sAreaID + "'");
        string tmp = String.Empty;
        if (mydv.Count == 1)
        {
            string[] ary = sFields.Split(',');
            for (int i = 0; i < ary.Length - 1; i++)
            {
                tmp += mydv[0][ary[i]] + ",";
            }
        }
        return tmp;
    }
    protected void btnGetInfo_Click(object sender, EventArgs e)
    {

    }

    //根据数据库中表的结构生成动态表格
    private Dictionary<string, List<string>> getTableInfo()
    {
        string sVer = SQLHelper.ExecuteString("select TOP 1 CValue from t_param where PCode='7' order by Code");
        Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>();
        //1.获取动态定义表中的数据表
        DataView tabledv = SQLHelper.ExecuteDataView("select * from vi_ReportTemplate where Ver = '" + sVer + "' order by OrderNo");
        //2.生成表格
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < tabledv.Count; i++)
        {
            string sType = String.IsNullOrEmpty(tabledv[i]["StatType"].ToString()) ? "" : tabledv[i]["StatType"].ToString() + "统计";
            dic.Add(tabledv[i]["FieldName"].ToString(), new List<string>() { tabledv[i]["FieldAlias"].ToString(), sType, tabledv[i]["Unit"].ToString() });
            hidTextList.Value += tabledv[i]["FieldName"].ToString() + ",";
            if (sType == "季度统计")
                disabledinfo.Value += tabledv[i]["FieldName"].ToString() + ",";
        }
        return dic;
    }

    private string getEditInfo(string sId)
    {
        string sVer = SQLHelper.ExecuteString("select TOP 1 CValue from t_param where PCode='7' order by Code");
        string rtn = String.Empty;
        DataView tabledv = SQLHelper.ExecuteDataView("select * from vi_ReportTemplate where Ver = '" + sVer + "' order by OrderNo");
        StringBuilder sb = new StringBuilder();
        sb.Append("select RA_ID,Area_ID,Years,Remark");
        for (int i = 0; i < tabledv.Count; i++)
        {
            sb.Append("," + tabledv[i]["FieldName"].ToString());
        }
        sb.Append(" from tb_ReportAnalysisOnline where RA_ID='" + sId + "'");
        DataView Infodv = SQLHelper.ExecuteDataView(sb.ToString());
        if (Infodv.Count != 0)
        {
            rtn += Infodv[0]["Area_ID"].ToString() + "|Area_ID,";
            rtn += Infodv[0]["Years"].ToString().Substring(0, 4) + "|Years,";
            rtn += Infodv[0]["Years"].ToString().Substring(4, 2) + "|Months,";
            rtn += Infodv[0]["Remark"].ToString() + "|Remark,";
            string tmp = String.Empty;
            for (int i = 0; i < tabledv.Count; i++)
            {
                tmp = Infodv[0][tabledv[i]["FieldName"].ToString()].ToString();
                if (!String.IsNullOrEmpty(tmp))
                    rtn += tmp + "|" + tabledv[i]["FieldName"].ToString() + ",";
            }
        }

        return rtn;
    }
}
